package czk.concrent.threadpool.deadlock;

import com.google.common.base.Stopwatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author chenzhangkun
 * @ClassName DeadLockDemo
 * @description: 子任务和主任务死锁互相等待的情况，
 * 日常开发中有这种场景，比如服务A的接口1调用服务B的接口2，服务B的接口2调用服务A的接口2，接口1和接口2如果默认的是同一个线程池，那么就会造成死锁，导致任务无法执行。
 * @date 2024年09月02日
 */
public class DeadLockDemo {
	public static void main(String[] args) throws InterruptedException {
		ExecutorService executorService = Executors.newFixedThreadPool(5);
		ExecutorService executorService2 = Executors.newFixedThreadPool(5);

		CountDownLatch countDownLatch = new CountDownLatch(5);
		Stopwatch stopwatch = Stopwatch.createStarted();
		for (int i = 0; i < 5; i++) {
			try {
				int finalI = i;
				CountDownLatch countDownLatch1=new CountDownLatch(1);
				executorService.execute(() -> {
					extracted(finalI,executorService,countDownLatch1);
					countDownLatch.countDown();
				});
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		countDownLatch.await();
		stopwatch.stop();
		System.out.println(stopwatch);
	}

	private static void extracted(int finalI,ExecutorService executorService,CountDownLatch countDownLatch) {
		executorService.execute(()->{
			System.out.println("当前线程" + Thread.currentThread().getName() + "开始执行任务" + finalI);
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			System.out.println("当前线程" + Thread.currentThread().getName() + "执行任务" + finalI + "结束");
			countDownLatch.countDown();

		});
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}
}
